package com.oceanstar.service.Impl;

import com.oceanstar.Pojo.*;
import com.oceanstar.mapper.AlertMapper;
import com.oceanstar.mapper.UserInfoMapper;
import com.oceanstar.service.IGridService;
import com.oceanstar.utils.JwtUtils;
import io.jsonwebtoken.Claims;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class GridServiceImpl implements IGridService {
    // 注入mapper
    private final UserInfoMapper userInfoMapper;
    private final AlertMapper alertMapper;
    // 构造器注入
    public GridServiceImpl(UserInfoMapper userInfoMapper, AlertMapper alertMapper) {
        this.alertMapper = alertMapper;
        this.userInfoMapper = userInfoMapper;
    }

    /*
     *网格员查看网格员绑定的老人列表
     */
    @Override
    public PageInfo<ElderBindingInfo> getGridElderly(Integer page, Integer pageSize, String name, String token) throws Exception {
        // 1. 验证网格员权限
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        Integer id = (Integer) claims.get("id");
        if (identity != 4) {
            throw new Exception("需为网格员权限");
        }

        int offset = (page - 1) * pageSize;

        Long total = userInfoMapper.countGridBindings(id, name);

        List<ElderBindingInfo> rows = userInfoMapper.selectGridBindings(id, offset, pageSize, name);

        PageInfo<ElderBindingInfo> info = new PageInfo<>();
        info.setTotal(total);
        info.setRows(rows);

        return info;
    }

    @Override
    public PageInfo<AlertHistoryDTO> getAlertHistory(Integer page, Integer pageSize, Integer elderlyId, String begin, String end, String token) throws Exception {
        // 1. 验证网格员权限
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        Integer id = (Integer) claims.get("id");
        if (identity != 4) {
            throw new Exception("需为网格员权限");
        }
        // 2. 计算分页参数
        int offset = (page - 1) * pageSize;

        // 3. 查询数据
        List<AlertHistoryDTO> rows = alertMapper.selectAlertHistory(id, elderlyId,
                begin, end,
                offset, pageSize);
        Long total = alertMapper.countAlertHistory(id, elderlyId, begin, end);

        // 4. 返回分页结果
        return new PageInfo<>(total, rows);

    }

    @Override
    public PageInfo<AlertPendingDTO> getPendingAlerts(Integer page, Integer pageSize, String token) throws Exception {
        // 1. 验证网格员权限
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        Integer id = (Integer) claims.get("id");
        if (identity != 4) {
            throw new Exception("需为网格员权限");
        }
        // 2. 计算分页参数
        int offset = (page - 1) * pageSize;

        // 3. 查询数据
        List<AlertPendingDTO> rows = alertMapper.selectPendingAlerts(id, offset, pageSize);
        Long total = alertMapper.countPendingAlerts(id);

        // 4. 返回分页结果
        return new PageInfo<>(total, rows);
    }

    @Override
    public void handleAlert(AlertHandleRequest request, String token) throws Exception {
        // 1. 验证网格员权限
        Claims claims = JwtUtils.parseToken(token);
        Integer identity = (Integer) claims.get("identity");
        Integer id = (Integer) claims.get("id");
        String gridName = (String) claims.get("name");
        if (identity != 4) {
            throw new Exception("需为网格员权限");
        }

        // 2. 验证报警是否存在且属于当前网格员
        AlertInfo alert = alertMapper.selectAlertById(request.getAlertId());
        if (alert == null) {
            throw new Exception("报警记录不存在");
        }
        if (!id.equals(alert.getGridId())) {
            throw new Exception("无权处理此报警记录");
        }
        // 3. 验证报警状态（只能处理未处理的报警）
        if ("已处理".equals(alert.getStatus())) {
            throw new Exception("该报警已处理，无法重复处理");
        }
        // 4. 构建处理人信息
        String handler = "网格员-" + gridName;

        // 5. 执行更新
        alertMapper.handleAlert(
                request.getAlertId(),
                request.getStatus(),
                request.getResult(),
                request.getPhotoUrl(),
                handler,
                id
        );
    }
}
